package com.mlnx.data.dao.iml;

import com.mlnx.common.form.PageForm;
import com.mlnx.common.utils.MyLog;
import com.mlnx.data.dao.SugarStore;
import com.mlnx.data.entity.SugarInfo;
import com.mlnx.data.pojo.form.SugarInfoForm;
import com.mlnx.data.pojo.vo.SugarInfoVo;
import com.mlnx.device.util.SortUtil;
import com.mlnx.service.base.properties.MutilDeviceProperties;
import org.shan.spring.mongodb.MongodbUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository("SugarMongoDB")
public class SugarMongoDB implements SugarStore {

    private MyLog log = MyLog.getLog(SugarMongoDB.class);

    @Autowired
    private MutilDeviceProperties mutilDeviceProperties;

    @PostConstruct
    @Override
    public void init() {

        log.info("开始初始化Sugar mongodb存储");

        try {
            Map<String, Sort.Direction> map = new HashMap<>();
            map.put("patientId", Sort.Direction.ASC);
            map.put("time", Sort.Direction.ASC);
            MongodbUtils.setIndex(mutilDeviceProperties.getStore().getSugarCollectionName(), map, true);
        } catch (Exception e) {
            log.error(e, "设置血糖索引失败，失败已经捕捉不影响使用");
        }

        log.info("初始化Sugar mongodb存储结束");
    }

    @Override
    public void save(SugarInfo sugarInfo) {
        MongodbUtils.save(sugarInfo, mutilDeviceProperties.getStore().getSugarCollectionName());
    }

    @Override
    public List<SugarInfo> getSugars(Integer patientId, Long startTime, Long endTime) {
        Criteria criteria = Criteria.where("patientId").is(patientId);
        criteria.and("time").gt(startTime).lt(endTime);
        Query query = Query.query(criteria);
        query.with(new Sort(Sort.Direction.ASC, "time"));

        List<SugarInfo> sugarInfos = MongodbUtils.find(SugarInfo.class, query, mutilDeviceProperties.getStore().getSugarCollectionName());

        return sugarInfos;
    }

    @Override
    public void updateSugar(SugarInfo sugarInfo) {
        Criteria criteria = Criteria.where("patientId").is(sugarInfo.getPatientId());
        criteria.and("time").is(sugarInfo.getTime());

        try {
            MongodbUtils.updateFirst(sugarInfo, criteria, mutilDeviceProperties.getStore().getSugarCollectionName());
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void deleteSugar(SugarInfo sugarInfo) {
        Criteria criteria = Criteria.where("patientId").is(sugarInfo.getPatientId());
        criteria.and("time").is(sugarInfo.getTime());

        Query query = Query.query(criteria);

        MongodbUtils.remove(query, mutilDeviceProperties.getStore().getSugarCollectionName());
    }

    @Override
    public SugarInfoVo getPageSugars(PageForm pageForm, SugarInfoForm sugarInfoForm) {
        Criteria criteria =new Criteria();
        if(sugarInfoForm!=null){
            if(sugarInfoForm.getDeviceId()!=null){
                criteria.and("deviceId").is(sugarInfoForm.getDeviceId()) ;
            }
            if(sugarInfoForm.getPatientId()!=null){
                criteria.and("patientId").is(sugarInfoForm.getPatientId()) ;
            }
            if(sugarInfoForm.getStartTime()!=null){
                criteria.and("time").gt(sugarInfoForm.getStartTime()).lt(sugarInfoForm.getEndTime());
            }

        }

        Query query = Query.query(criteria);
        query.skip((pageForm.getCurrent() - 1) * pageForm.getSize());
        query.limit(Math.toIntExact(pageForm.getSize()));
        if(sugarInfoForm!=null){
            if(sugarInfoForm.getSorter()!=null && !"{}".equals(sugarInfoForm.getSorter())){
                Map<String,String> map= SortUtil.parseSorter(sugarInfoForm.getSorter());

                for (String str:map.keySet()){
                    query.with(new Sort(Sort.Direction.valueOf(map.get(str)), str));
                }
            }
        }
        List<SugarInfo> sugarInfos = MongodbUtils.find(SugarInfo.class, query, mutilDeviceProperties.getStore().getSugarCollectionName());
        Integer total = Math.toIntExact(MongodbUtils.count(new Query(criteria), mutilDeviceProperties.getStore().getSugarCollectionName()));
        SugarInfoVo sugarInfoVo =new SugarInfoVo();
        sugarInfoVo.setRecords(sugarInfos);
        sugarInfoVo.setTotal(total);
        sugarInfoVo.setSize(Math.toIntExact(pageForm.getSize()));
        sugarInfoVo.setCurrent(Math.toIntExact(pageForm.getCurrent()));
        return sugarInfoVo;
    }


}
